var express = require('express');
var multer = require('multer');
var fs = require('fs');
var mongoose = require('mongoose');
var Album = mongoose.model('Album');
var AlbumName = mongoose.model('AlbumName');
var upload = multer({
  dest:'upimgs'
});
var router = express.Router();

// var albumName = require('./albumName.json');
// var albums = new require('./albums.json');
var currentAlbum = "默认相册";
router.get('/', async function(req, res){
  let albumName = await AlbumName.find();
  console.log(albumName);
  res.locals.albumName = albumName;
  // console.dir(albums[currentAlbum]);
  let list = await Album.find({albumName:currentAlbum});
  res.locals.album = list;
  res.render('album_index');
});
router.post('/upimg',upload.single('image'), async function(req, res, next){
  // console.log(req.file);
  // console.log(currentAlbum);
  // let set=[];
  // if(albums[currentAlbum]){
  //   set = albums[currentAlbum];
  // }
  // set.push(req.file);
  // albums[currentAlbum] = set;
  // console.log(albums[currentAlbum]);
  // fs.writeFileSync(__dirname+"/albums.json",JSON.stringify(albums));
  var album = new Album({
    filename:req.file.filename,
    albumName:currentAlbum,
    createTime:new Date()
  });
  await album.save();
  res.send(req.file);
});
router.get('/currentAlbum/:name',function(req, res){
  var name = req.params.name;
  if(name){
    currentAlbum = req.params.name;
  }else {
    currentAlbum = "默认相册";
  }
  res.send(currentAlbum);
});

router.get('/createAlbum/:name', async function(req, res){
  var alname = req.params.name;
  // console.log(name);
  // let flag = false;
  // if(name){
  //   for(name_item of albumName){
  //     if(name_item==name)
  //     flag=true
  //   }
  //   if(flag == true){
  //     res.send('error');
  //     flag = false;
  //   }else{
  //   albumName.push(name);
  //   albums[albumName]=[];
  //   fs.writeFileSync(__dirname+"/albumName.json", JSON.stringify(albumName));
  //   fs.writeFileSync(__dirname+"/albums.json", JSON.stringify(albums));
  //   }
  console.log(alname);
  let a = await AlbumName.find({name:alname});
  console.log(a);
  if(a.length==0){
    console.log(alname);
    let albumName = new AlbumName({
      name:alname
    });
    console.log(albumName);
    await albumName.save();
  }

  res.send(alname);
});

router.get('/img/:filename', function(req, res){
  fs.createReadStream('upimgs/'+req.params.filename).pipe(res);
});


module.exports = router;
